package com.aube.interact;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aube.interact.controller.DataManager;
import com.aube.interact.model.GoodsItem;
import com.aube.interact.model.OptionItem;
import com.aube.interact.model.OptionResultModel;
import com.aube.interact.model.TimeLinePiece;
import com.aube.interact.util.Utils;
import com.aube.rvi.BitmapListener;
import com.aube.rvi.CommonDataLoader;
import com.aube.rvi.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/3/22.
 */
public class CardQANew extends BaseCardNew {

    private Context context;
    private View mGoodsLayout, mRoot;

    private ImageView mLogo;
    private TextView mTitle, mCountdown, mQAResult;

    private View mTop;

    private TagFlowLayout mQaView;

    private int margin = 0;
    private int marginBottom = 0;

    private TagAdapter mAdapter;
    private String[] mLabel;

    private View mClose, mQARoot;

    private AtomicBoolean mCallSended = new AtomicBoolean(false);
    private AtomicBoolean mRevealResult = new AtomicBoolean(false);
    private int mRightAnswerIndex = -1;

    private int selectedIndex = -1;

    private int mTxtHeight = 0;

    private String mMessage = null;
    private List<GoodsItem> mGoodsList = null;

    public CardQANew(Context context) {
        this(context, null);
    }

    public CardQANew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CardQANew(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        mRoot = LayoutInflater.from(getContext()).inflate(R.layout.aube_plugin_layout_card_qa_new, this);

        mLogo = (ImageView) mRoot.findViewById(R.id.card_qa_logo);
        mTitle = (TextView) mRoot.findViewById(R.id.card_qa_title);

        mCountdown = (TextView) mRoot.findViewById(R.id.card_qa_countdown);

        mTop = mRoot.findViewById(R.id.card_qa_top);
        mTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mQARoot.getVisibility() != View.VISIBLE) {
                    swithWindow(false, mQARoot);
                }
            }
        });

        mGoodsLayout = findViewById(R.id.card_qa_layout);

        mCollapse = (ImageView) findViewById(R.id.card_qa_collapse);

        mClose = findViewById(R.id.card_qa_close);
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

        mQaView = (TagFlowLayout) findViewById(R.id.card_qa);
        mQARoot = findViewById(R.id.card_qa_root);
        mQAResult = (TextView) findViewById(R.id.card_qa_result);

        mCollapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swithWindow(mQARoot.getVisibility() == View.VISIBLE, mQARoot);
                requestLayout();
            }
        });

        margin = getResources().getDimensionPixelOffset(R.dimen.card_margin_space);
        marginBottom = getResources().getDimensionPixelOffset(R.dimen.card_margin_bottom);

        mMinHeight = marginBottom;
        mTxtHeight = getResources().getDimensionPixelOffset(R.dimen.card_qa_result_height);
    }

    public void updateCountDown(String time) {
        if(mRevealResult.get())
            return;
        mCountdown.setText(time);

        if(iSender != null && mData != null && StringUtils.isBlank(time) && !mCallSended.get()) {
            mCallSended.set(true);
            mRevealResult.set(true);
            iSender.startSync(mData.rid, false);
            notifyDataChanged();

            //当有奖品的时候才提示
            if(StringUtils.isNotBlank(mMessage) && mGoodsList != null && mGoodsList.size() > 0)
                animResult(mMessage);
        }
    }

    @Override
    public void init(final TimeLinePiece data, String mVideoId) {
        super.init(data, mVideoId);
        mTitle.setText(data.title);
        if(StringUtils.isNotBlank(data.getImgUrl())) {
            CommonDataLoader.getInstance(context).startImageLoader(mLogo, data.getImgUrl(), 0, 0);
        } else {
            mLogo.setVisibility(View.GONE);

            CommonDataLoader.getInstance(context).startImageRequest(data.getImgTag(), 0, 0, new BitmapListener() {
                @Override
                public void onResponse(Bitmap response) {
                    if (response == null)
                        return;

                    SpannableStringBuilder builder = new SpannableStringBuilder("[star]  " + data.title);
                    builder.setSpan(new ExtendImageSpan(getContext(), response, getTextHeight()), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mTitle.setText(builder);
                }
            });
        }

        setupLabels();
        fillData();

        if(data.isCardFold()) {
            mQARoot.setVisibility(View.INVISIBLE);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mQARoot.getLayoutParams();
            params.height = marginBottom;
            mQARoot.setLayoutParams(params);

            mCollapse.setImageResource(R.drawable.icon_arrowup);
        } else {
            mCollapse.setImageResource(R.drawable.icon_arrowdown);
        }
    }

    @Override
    public String getType() {
        return TYPE_QA;
    }

    private float getTextHeight() {
        Paint paint = mTitle.getPaint();
        return Math.abs(paint.ascent());
    }

    public void doNext() {
        selectedIndex = DataManager.getInstance(context).getIndex(mData.rid);
        if(selectedIndex >= 0) {
            mCountdown.setText("");
            mRevealResult.set(true);

            //已选的结果直接展示出来,除非有中奖提示
            String msg = DataManager.getInstance(getContext()).getQAResult(mData.rid);
            if(StringUtils.isNotBlank(msg)) {
                mQAResult.setVisibility(View.VISIBLE);
            }

            setupLabels();

            if(iSender != null)
                iSender.startSync(mData.rid, false);
            notifyDataChanged();
        }
    }

    private void notifyDataChanged() {
        int childCount = mQaView.getChildCount();
        for(int i=0; i<childCount; i++) {
            View v = mQaView.getChildAt(i);
            initView(v, i);
        }
    }

    private void animShow(final View v) {
//        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
//        anim.setDuration(100);
//        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                float fraction = (float) animation.getAnimatedValue();
//                v.setScaleX(fraction);
//                v.setScaleY(fraction);
//            }
//        });
//        anim.start();
        v.setVisibility(View.VISIBLE);
    }

    private void initView(View v, int position) {
        View layout = v.findViewById(R.id.label_text_layout);
        TextView tv = (TextView) v.findViewById(R.id.label_text);
        tv.setText(mData.getOptionValue(position));

        TextView ratio = (TextView) v.findViewById(R.id.label_ratio);
        String rStr = mLabel[position];
        if(StringUtils.isNotBlank(rStr)) {
            ratio.setText(rStr);

            if(ratio.getVisibility() != View.VISIBLE) {
                animShow(ratio);
            }
        }

        ImageView img = (ImageView) v.findViewById(R.id.label_answer);

        if(selectedIndex == position) {
            tv.setTextColor(getResources().getColor(R.color.white));
            ratio.setTextColor(getResources().getColor(R.color.white));
        } else {
            tv.setTextColor(getResources().getColor(R.color.black));
            ratio.setTextColor(getResources().getColor(R.color.black));
        }

        //答案出来了之后再显示img
        if(selectedIndex == position) {
            layout.setSelected(true);

            if(mRevealResult.get()) {
                if(mRightAnswerIndex == position) {
                    img.setImageResource(R.drawable.icon_right);
                    img.setVisibility(View.VISIBLE);
                } else if(mRightAnswerIndex >= 0) {
                    img.setImageResource(R.drawable.icon_wrong);
                    img.setVisibility(View.VISIBLE);
                } else {
                    img.setVisibility(View.GONE);
                }
            } else
                img.setVisibility(View.GONE);
        } else {
            layout.setSelected(false);

            if(mRightAnswerIndex == position && mRevealResult.get()) {
                img.setImageResource(R.drawable.icon_right);
                img.setVisibility(View.VISIBLE);
            } else {
                img.setVisibility(View.GONE);
            }
        }
    }

    public void fillData() {
        mAdapter = new TagAdapter<String>(mLabel) {

            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                View v = LayoutInflater.from(context).inflate(R.layout.aube_plugin_item_label, mQaView, false);
                initView(v, position);
                return v;
            }
        };

        mQaView.setAdapter(mAdapter);

        mQaView.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                try {
                    if (position == selectedIndex)
                        return true;

//                    if (mRevealResult.get())
//                        return true;
//
//                    if (mData == null)
//                        Toast.makeText(getContext(), mLabel[position], Toast.LENGTH_SHORT).show();
//                    else
//                        report(mData.rid, mData.getOptionId(position), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });


        mQaView.setOnSelectListener(new TagFlowLayout.OnSelectListener() {

            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                try {
                    //TODO:多次点击的话,这里有一个crash
                    if (selectPosSet == null || !selectPosSet.iterator().hasNext())
                        return;
                    int position = selectPosSet.iterator().next();
                    if (position == selectedIndex)
                        return;

                    if (mRevealResult.get())
                        return;

                    DataManager.getInstance(getContext()).update(mData.rid, position);

                    //change background
//                setupLabels(null);

                    String cancelId = null;
                    String optionId = mData.getOptionId(position);
                    if (selectedIndex >= 0)
                        cancelId = mData.getOptionId(selectedIndex);
                    if (mData == null)
                        Toast.makeText(getContext(), mLabel[position], Toast.LENGTH_SHORT).show();
                    else
                        report(mData.rid, optionId, cancelId, false);

                    DataManager.getInstance(context).updateOptionCount(cancelId, true);
                    DataManager.getInstance(context).updateOptionCount(optionId, false);

                    selectedIndex = position;

                    notifyDataChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 动态展示result
     */
    private void animResult(String result) {
        mQAResult.setText(result);
        float startValue = mQARoot.getHeight();
        float endValue = mQaView.getHeight() + mTxtHeight + mMinHeight;

        final ValueAnimator anim = ValueAnimator.ofFloat(startValue, endValue);
        anim.setDuration(200);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mQARoot.getLayoutParams();
                params.height = (int) value;
                mQARoot.setLayoutParams(params);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mQAResult.setAlpha(0);
                mQAResult.setVisibility(View.VISIBLE);
            }
        });

        AnimatorSet set = new AnimatorSet();
        Animator alphaAnim = ObjectAnimator.ofFloat(mQAResult, "alpha", 0, 1);
        alphaAnim.setDuration(200);

        set.playSequentially(anim, alphaAnim);
        set.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int height = mGoodsLayout.getMeasuredHeight();// + marginBottom;// + margin;

        int flowWidth = mQaView.getMeasuredWidth();
        int topWidth = mTop.getMeasuredWidth();

        int width = flowWidth > topWidth ? flowWidth : topWidth;

        if(topWidth > flowWidth) {
            ViewGroup.LayoutParams params = mQaView.getLayoutParams();
            params.width = topWidth;
        }
        if(topWidth < flowWidth) {
            ViewGroup.LayoutParams params = mTop.getLayoutParams();
            params.width = flowWidth;
        }

        ViewGroup.LayoutParams params = mQAResult.getLayoutParams();
        params.width = width + 2*margin;

//        int mTxtHeight = mQAResult.getMeasuredHeight();

//        mQaView.measure(MeasureSpec.makeMeasureSpec(flowWidth, MeasureSpec.EXACTLY), 0);
//        mContentHeight = mQaView.getMeasuredHeight();
        mQARoot.measure(View.MeasureSpec.makeMeasureSpec(flowWidth, View.MeasureSpec.EXACTLY), 0);
        mContentHeight = mQARoot.getMeasuredHeight();

        measureChild(getChildAt(0), View.MeasureSpec.makeMeasureSpec(width + 2 * margin, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));

        setMeasuredDimension(View.MeasureSpec.makeMeasureSpec(width + 2 * margin, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
    }


    @Override
    public void syncData(OptionResultModel response) {
        //reset data & notifydatasetchange
        //init mLabels
        try {
            setupLabels();
            notifyDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearData() {
        mMessage = null;
    }

    public void report(String rid, String msg, List<GoodsItem> goodsItemList) {
        String id = DataManager.getInstance(context).getSelectedOptionId(mData.rid);
        if(StringUtils.isNotBlank(id) && id.equalsIgnoreCase(rid)) {
            mMessage = msg;
            mGoodsList = goodsItemList;

            if (DataManager.getInstance(getContext()).update(mGoodsList)) {
                DataManager.getInstance(getContext()).updateQAResult(rid, msg);

                //将奖品加入到商品列表当中
                if (iSender != null)
                    iSender.onAddRewardGoods(mGoodsList);
            }
        } else {
            mMessage = null;
            mGoodsList = null;
        }
    }

    private synchronized void setupLabels() {
        if(mData == null)
            return;
        HashMap<String, Integer> mSet = new HashMap<>();
        int count = 0;
        for(OptionItem item : mData.getOptions()) {
            count += DataManager.getInstance(context).getOptionCount(item.optionId);

        }

        if(count > 0) {
            for (OptionItem item : mData.getOptions()) {
                mSet.put(item.optionId, Utils.calPercentInt(count, DataManager.getInstance(context).getOptionCount(item.optionId)));
            }

            reSortData(mSet);
        }
        mLabel = new String[mData.optionSize()];
        int index = 0;
        for(OptionItem item : mData.getOptions()) {
//            mLabel[index] = item.optionValue + (mSet.containsKey(item.optionId)?appendPercentStr(mSet.get(item.optionId)):"");
            mLabel[index] = mSet.containsKey(item.optionId)?appendPercentStr(mSet.get(item.optionId)):"";

            if(mRightAnswerIndex < 0) {
                //find the right answer
                if (item.isRightAnswer())
                    mRightAnswerIndex = index;
            }

            index++;
        }
    }

}
